﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Marbles.Core.Authentication;
using System.IO;
using Marbles.Core.Content.Sites;
using System.Web.SessionState;

namespace Marbles.Web.Admin.Downloads
{
    public abstract class DownloadHandler : IHttpHandler, IRequiresSessionState
    {
        public Marbles.Core.Authentication.AuthenticationProvider AuthenticationProvider
        {
            get { return Marbles.Core.Authentication.AuthenticationProvider.CreateProviderInstance(); }
        }

        public bool IsEditor
        {
            get
            {
                IToken token = this.AuthenticationProvider.CurrentToken;
                return (token == null) ? false : token.IsEditor;
            }
        }

        public SiteDefinition CurrentWeb
        {
            get { return SiteDefinition.GetCurrent(); }
        }

        public bool IsAdministrator
        {
            get
            {
                IToken token = this.AuthenticationProvider.CurrentToken;
                return (token == null) ? false : token.IsAdministrator;
            }
        }

        public bool isViewer
        {
            get
            {
                IToken token = this.AuthenticationProvider.CurrentToken;
                return (token == null) ? true : token.IsViewer;
            }
        }

        public string Username
        {
            get
            {
                IToken token = this.AuthenticationProvider.CurrentToken;
                return (token == null) ? "" : token.Username;
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            if ((!IsAdministrator) && (!IsEditor))
            {
                context.Response.StatusCode = 404;
                context.Response.ContentType = "text/html";
                context.Response.StatusDescription = "File Not Found.";
                context.Response.End();
                return;
            }

            context.Response.ContentType = "text/comma-separated-values";
            context.Response.AddHeader("content-disposition", "attachment;filename=" + Path.GetFileNameWithoutExtension(context.Server.MapPath(context.Request.Path)) + ".csv");
            Download(context.Response);
            context.Response.Flush();
            context.Response.End();
        }

        public abstract void Download(HttpResponse response);

    }
}